import axios from 'axios';
import qs from 'qs';
import localTools from 'src/utils/LocalStorageTools';
import {Message} from 'element-ui';
const token = localTools.get('token');
const instance = axios.create({
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Type': 'application/json',

  },
  transformRequest: [function (data, config) {
    if (config['Content-Type'] == 'application/x-www-form-urlencoded') data = qs.stringify(data);
    if (config['Content-Type'] == 'application/json') data = JSON.stringify(data)
    return data;
  }],
  // withCredentials: true,
  timeout: 60000
});
instance.interceptors.request.use(function (config) {

  if (localTools.get('token')) {
    config.headers.Authorization = `${token.token_type} ${token.access_token}`;
  }
  config.headers['accept-language'] = 'zh-CN'
  return config;
}, function (error) {

  return Promise.reject(error);
});
instance.interceptors.response.use(function (response) {

  return response;
}, function (error) {

  return Promise.reject(error);
});
let arr = []

function init(obj) {
  arr.push(obj)
}

function del(obj) {
  arr.splice(arr.indexOf(obj), 1)
}


function ajax({url = '', data = {}, showMsg = false, method = 'get', config = {}}) {

  let urlLastString = url.split('/');
  let str = urlLastString[urlLastString.length - 1].toUpperCase()
  if (str.indexOf('SAVE') > -1 || str.indexOf('SET') > -1) {
    showMsg = true
  }

  let obj = {url, data, method, showMsg, config}
  init(obj)
  let index = arr.length - 1
  if (method == 'get') {
    data = {
      params: {
        ...data,
        timestamp: Math.random() * 100000000000000000
      }
    }
  }
  return instance[method](url, data, config)
    .then((res) => {

      let urlapilinks = obj.url.split('/')
      let urlapilink = urlapilinks[urlapilinks.length - 1]
      del(obj)
      if (res.data) {
        let msg = res.data.msg || res.data.RMessage || res.data.msgTitle || res.data.Message || ''
        if (res.data.result === false || (res.data.code && res.data.code != 1000)) {
          if (urlapilink == 'IdentificationInvoice') {
            return res.data
          }
          return Promise.reject({message: msg || res.statusText, code: res.status, response: res.data})
        } else {
          //showMsg && msg && Toast.success(msg)
          return res.data
        }
      } else {
        return Promise.reject({message: res.statusText, code: res.status, response: res.data})
      }
    }).catch(({response, message}) => {
      console.log('catch',response)
      del(obj)
      let msg = (response && response.data && (response.data.Message || response.data.error_description ||
        response.data.msg || response.msg || response.MsgType || response.data.RMessage || response.data.Message || response.data.msgTitle
      )) || message
      if (response && response.code === "1002" && token) {

        return instance.post('/token', {
          'refresh_token': token.refresh_token,
          'grant_type': 'refresh_token'
        }, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
          localTools.set('token',res)
          return ajax({url, data, showMsg, method, config})
        }).catch(err => {
          localTools.remove('token')
          return Promise.reject('1080长时间不登录,请重新登录')
        })
      } else {

        showMsg && msg && Message.error(msg);
        return Promise.reject(response)
      }

    })

}

Date.prototype.toJSON = function () {

  return this.Format('yyyy-MM-dd hh:mm:ss')
}
Date.prototype.toISOString = function () {

  return this.Format('yyyy-MM-dd hh:mm:ss')
}
Date.prototype.Format = function (fmt = 'yyyy-MM-dd') { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1,
        (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export default ajax
